package cloud.kiko.psn.filter.global;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;


@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //获取请求头
        MultiValueMap<String, String> headers = request.getHeaders();
        String auth = headers.getFirst("auth");
        InetSocketAddress ra = request.getRemoteAddress();
        if ("kiko".equals(auth)) {
            //往MQ发送消息
            if (ra != null) {
                rabbitTemplate.convertAndSend("exchange-1", "routing-key-1",
                        ra.getAddress().getCanonicalHostName() + ra.getPort() + "-具有权限");
            }
            //放行
            return chain.filter(exchange);
        } else {
            //往MQ发送消息
            if (ra != null) {
                rabbitTemplate.convertAndSend("exchange-1", "routing-key-2",
                        ra.getAddress().getHostName() + ra.getPort() + "-没有权限");
            }
            //设置响应状态码，结束请求在过滤器链上传递
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        //本过滤器排序优先级：数字越小，越先执行
        //所以，作为登录过滤器，应该在请求转发到微服务之前执行过滤逻辑
        return 0;
    }
}
